package com.dwxt.stadium.service;

import com.alibaba.fastjson.JSONObject;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.PurchaseMethod;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.util.MD5Utils;
import com.dwxt.common.util.OkHttpUtils;
import com.dwxt.common.util.PartyUtil;
import com.dwxt.common.wxpay.WXPayUtil;
import com.dwxt.stadium.constant.OrderStatus;
import com.dwxt.stadium.dao.PayOrderMapper;
import com.dwxt.stadium.entity.PayOrder;
import com.dwxt.stadium.entity.PayOrderExample;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.management.OperationsException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class StadiumService {

    @Value("${dongMei.url}")
    private String dongMeiUrl;

    @Autowired
    private PayOrderMapper orderMapper;

    public BaseResult bookStadium(String startTime, String endTime, String productIds, Integer onlinePaymentMethod) throws Exception {
        String dongMeiUserId = PartyUtil.getCurrentDongMeiUserId();
        if (StringUtils.isBlank(dongMeiUserId) || "null".equals(dongMeiUserId)) {
            return BaseResult.build(StatusCode.BOOK_FAil);
        }
        //请求动美接口，生成订单并生成本地订单
        //1.请求动美接口，生成预定订单
        JSONObject object = createOrderReturnInfo(startTime, endTime, productIds);
        if (object.getInteger("errorcode") != 0) {
            log.error("生成订单失败" + object.toJSONString());
            return BaseResult.build(object.getInteger("errorcode"), object.getString("errormessage"), null);
        } else {
            JSONObject orderValue = object.getJSONObject("value");
            String orderId = orderValue.getString("OrderId");
            //2.请求动美接口，支付订单，获取微信或支付宝参数
            JSONObject result = orderPay(orderId, onlinePaymentMethod);
            int errorcode = result.getInteger("errorcode");
            if (errorcode != 0) {
                log.error("订单信息" + object.toJSONString());
                log.error("支付出问题" + result.toJSONString());
                return BaseResult.build(result.getInteger("errorcode"), result.getString("errormessage"), null);
            } else {
                //生成本地订单
                JSONObject payResult = result.getJSONObject("value");
                createLocalOrder(orderValue, payResult, onlinePaymentMethod);
                //构造返回数据
                //payResult.put("orderId", orderId);
                Map<String, String> repData = buildResult(orderId, payResult);
                return BaseResult.ok(repData);
            }
        }
    }

    private Map<String, String> buildResult(String orderId, JSONObject payResult) throws Exception {
        Map<String, String> repData = new HashMap<>();
        String aliPrePaystr = payResult.getString("AliPrePaystr");
        if (StringUtils.isNotBlank(aliPrePaystr)) {
            repData.put("orderId", orderId);
            repData.put("orderString", aliPrePaystr);
        } else {
            JSONObject orderInfo = payResult.getJSONObject("OrderInfo");
            repData.put("appid", orderInfo.getString("AppId"));
            repData.put("partnerid", "1592859031");
            repData.put("prepayid", orderInfo.getString("PrePayId"));
            repData.put("package", "Sign=WXPay");
            repData.put("noncestr", orderInfo.getString("NonceStr"));
            String time = String.valueOf(System.currentTimeMillis() / 1000);
            repData.put("timestamp", time);
            String sign = WXPayUtil.generateSignature(repData, "fuckweixinapikeyfackweixinapikey");
            repData.put("sign", sign);
            //repData.put("orderId", orderId);
        }
        return repData;
    }

    private void createLocalOrder(JSONObject orderValue, JSONObject payResult, Integer onlinePaymentMethod) {

        String orderId = orderValue.getString("OrderId");
        String detail = orderValue.getString("Detail");
        String orderNumber = orderValue.getString("OrderNumber");
        double amount = orderValue.getDouble("Amount");
        String username = orderValue.getString("Username");
        Double goldBalance = orderValue.getDouble("GoldBalance");
        Double balance = orderValue.getDouble("Balance");
        String memberDto = orderValue.getString("MemberDto");

        PayOrder order = new PayOrder();
        order.setId(orderId);
        order.setAmount(amount);
        order.setBalance(balance);
        order.setDetail(detail);
        order.setGoldBalance(goldBalance);
        order.setMemberDto(memberDto);
        order.setOrderNumber(orderNumber);
        order.setUsername(username);
        order.setStatus(OrderStatus.PLACE);
        order.setUserId(PartyUtil.getCurrentUserId());

        orderMapper.insertSelective(order);
        //订单存入redis
        //redisService.set("order_" + order.getId(), order.getId(), (long) 15 * 60);
    }

    private JSONObject orderPay(String orderId, Integer onlinePaymentMethod) {
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderId);
        params.put("UseBalance", "false");
        params.put("UseGold", "false");
        String url = dongMeiUrl + "OrderPay";
        if (onlinePaymentMethod == 2) {
            params.put("UseMemberCard", "true");
        } else {
            params.put("UseMemberCard", "false");
            params.put("OnlinePaymentMethod", onlinePaymentMethod.toString());
        }
        Map<String, String> headerMap = getHeaderMap();
        String result = OkHttpUtils.formPost(url, params, headerMap);
        return JSONObject.parseObject(result);
    }

    private JSONObject createOrderReturnInfo(String startTime, String endTime, String productIds) {
        String[] productIdArr = productIds.split(",");
        String url = dongMeiUrl + "CreateOrderReturnInfo";
        Map<String, String> params = new HashMap<>();
        for (int i = 0; i < productIdArr.length; i++) {
            String productId = "Items[" + i + "].ProductId";
            String start = "Items[" + i + "].StartTime";
            String end = "Items[" + i + "].EndTime";
            params.put(productId, productIdArr[i]);
            params.put(start, startTime);
            params.put(end, endTime);
        }
        Map<String, String> headers = getHeaderMap();
        String result = OkHttpUtils.formPost(url, params, headers);
        return JSONObject.parseObject(result);
    }

    private Map<String, String> getHeaderMap() {
        Map<String, String> headers = new HashMap<>();
        Long time = System.currentTimeMillis();
        String dongMeiUserId = PartyUtil.getCurrentDongMeiUserId();
        String signature = MD5Utils.MD5Encode("dongmeiwangApp" + dongMeiUserId + time);
        headers.put("user_id", dongMeiUserId);
        headers.put("time", time.toString());
        headers.put("Signature", signature);
        headers.put("IsNeedLogin", "true");
        return headers;
    }


    public BaseResult refund(String orderId, String reason) {
        //申请动美退款
        JSONObject result = applyUnsubscribeOrder(orderId, reason);
        int errorcode = result.getInteger("errorcode");
        if (errorcode != 0) {
            return BaseResult.build(result.getInteger("errorcode"), result.getString("errormessage"), null);
        } else {
            PayOrder order = orderMapper.selectByPrimaryKey(orderId);
            if (order != null) {
                order.setStatus(OrderStatus.REQUEST_REFUND);
                orderMapper.updateByPrimaryKeySelective(order);
            }
            return BaseResult.ok();
        }
    }

    private JSONObject applyUnsubscribeOrder(String orderId, String reason) {
        String url = dongMeiUrl + "ApplyUnsubscribeOrder";
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderId);
        if (StringUtils.isNotBlank(reason)) {
            params.put("Reason", reason);
        }
        Map<String, String> headerMap = getHeaderMap();
        String s = OkHttpUtils.formPost(url, params, headerMap);
        return JSONObject.parseObject(s);
    }

    public List<PayOrder> selectOrderByStatus(List<String> status) {
        PayOrderExample example = new PayOrderExample();
        example.createCriteria().andStatusIn(status);
        return orderMapper.selectByExample(example);
    }

    public void updateOrder(PayOrder order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    public BaseResult bookStadiumDiff(String startTimes, String endTimes, String productIds, Integer onlinePaymentMethod, Double fee, String companyId, String memberId) throws Exception {
        String dongMeiUserId = PartyUtil.getCurrentDongMeiUserId();
        if (StringUtils.isBlank(dongMeiUserId) || "null".equals(dongMeiUserId)) {
            return BaseResult.build(StatusCode.BOOK_FAil);
        }
        //请求动美接口，生成订单并生成本地订单
        //1.请求动美接口，生成预定订单
        JSONObject object = createOrderReturnInfoDiff(startTimes, endTimes, productIds);
        if (object.getInteger("errorcode") != 0) {
            log.error("生成订单失败" + object.toJSONString());
            return BaseResult.build(object.getInteger("errorcode"), object.getString("errormessage"), null);
        } else {
            JSONObject orderValue = object.getJSONObject("value");
            String orderId = orderValue.getString("OrderId");
            //2.请求动美接口，支付订单，获取微信或支付宝参数
            //会员卡支付
            /*if (onlinePaymentMethod == 2) {
                String url = dongMeiUrl + "payByMemberCard";
                Map<String, String> params = new HashMap<>();
                params.put("memberId", memberId);
                params.put("fee", fee.toString());
                params.put("companyId", companyId);
                params.put("password", "123456");
                String result = OkHttpUtils.formPost(url, params, null);
                if (!result.equalsIgnoreCase("\"success\"")) {
                    log.error("会员卡支付失败" + result);
                    return BaseResult.build(StatusCode.ORDER_PURCHASE_FAIL);
                }
            }*/
            JSONObject result = orderPay(orderId, onlinePaymentMethod);
            int errorcode = result.getInteger("errorcode");
            if (errorcode != 0) {
                log.error("订单信息" + object.toJSONString());
                log.error("支付出问题" + result.toJSONString());
                return BaseResult.build(result.getInteger("errorcode"), result.getString("errormessage"), null);
            } else {
                //生成本地订单
                JSONObject payResult = result.getJSONObject("value");
                createLocalOrder(orderValue, payResult, onlinePaymentMethod);
                //构造返回数据
                //payResult.put("orderId", orderId);
                if (onlinePaymentMethod == 2) {
                    return BaseResult.ok();
                } else {
                    Map<String, String> repData = buildResult(orderId, payResult);
                    return BaseResult.ok(repData);
                }
            }
        }
    }

    private JSONObject createOrderReturnInfoDiff(String startTimes, String endTimes, String productIds) {
        String[] productIdArr = productIds.split(",");
        String[] startTimeArr = startTimes.split(",");
        String[] endTimeArr = endTimes.split(",");
        String url = dongMeiUrl + "CreateOrderReturnInfo";
        Map<String, String> params = new HashMap<>();
        for (int i = 0; i < productIdArr.length; i++) {
            String productId = "Items[" + i + "].ProductId";
            String start = "Items[" + i + "].StartTime";
            String end = "Items[" + i + "].EndTime";
            params.put(productId, productIdArr[i]);
            params.put(start, startTimeArr[i]);
            params.put(end, endTimeArr[i]);
        }
        Map<String, String> headers = getHeaderMap();
        String result = OkHttpUtils.formPost(url, params, headers);
        return JSONObject.parseObject(result);
    }

    public BaseResult selectCard(String companyId, String userId) {
        if (StringUtils.isBlank(userId)) {
            userId = PartyUtil.getCurrentDongMeiUserId();
        }
        String url = dongMeiUrl + "/my/GetCard?userId=" + userId + "&companyId=" + companyId;
        String s = OkHttpUtils.synGet(url, null);
        //JSONArray jsonArray = JSONArray.fromObject(s);
        List<Object> objects = JsonUtils.jsonToList(s, Object.class);
        return BaseResult.ok(objects);
    }
}
